package com.demo.arch.datapulsedemo.v3_reliable.client;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 邮件服务客户端（模拟Feign调用外部邮件服务）
 * 
 * 实际项目中应该是：
 * 
 * @FeignClient(name = "email-service", url = "${email.service.url}")
 *                   public interface EmailServiceClient {
 *                   @PostMapping("/api/email/send")
 *                   EmailResult sendEmail(@RequestBody EmailRequest request);
 *                   }
 * 
 * @author DataPulse Team
 */
@Slf4j
@Component
public class EmailServiceClient {

  private final Random random = new Random();

  /**
   * 发送邮件（模拟调用外部服务）
   * 
   * @param email          收件人邮箱
   * @param recipientName  收件人姓名
   * @param subject        邮件主题
   * @param content        邮件内容
   * @param attachmentPath 附件路径
   * @return 发送结果
   */
  public EmailResult sendEmail(String email, String recipientName, String subject,
      String content, String attachmentPath) {
    log.info("调用外部邮件服务 - 收件人: {} <{}>", recipientName, email);

    try {
      // 模拟网络延迟
      Thread.sleep(50);

      // 模拟80%成功率
      boolean success = random.nextInt(10) < 8;

      if (success) {
        log.info("邮件发送成功: {}", email);
        return EmailResult.success("邮件发送成功");
      } else {
        log.warn("邮件发送失败: {} - 外部服务返回失败", email);
        return EmailResult.failure("外部邮件服务繁忙，请稍后重试");
      }

    } catch (Exception e) {
      log.error("调用邮件服务异常: {}", email, e);
      return EmailResult.failure("调用邮件服务异常: " + e.getMessage());
    }
  }

  /**
   * 邮件发送结果
   */
  @Data
  @AllArgsConstructor
  public static class EmailResult {
    private boolean success;
    private String message;

    public static EmailResult success(String message) {
      return new EmailResult(true, message);
    }

    public static EmailResult failure(String message) {
      return new EmailResult(false, message);
    }
  }
}
